﻿using JESAI.MonacoRoslynComplete.Builders;
using Microsoft.Extensions.FileProviders;
using System.Configuration;
using System.Reflection;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class DependencyInjectionExtensions
    {
        public static IServiceCollection AddMonacoRoslynComplete(this IServiceCollection services)
        {
            services.AddHttpClient();
            IConfiguration configuration = services.BuildServiceProvider().GetService<IConfiguration>().GetSection("MonacoRoslynComplete");
            IMonacoRoslynCompleteBuilder builder = new DefaultMonacoRoslynCompleteBuilder(services, configuration);
            builder.UseMySqlStorage().InitStorage();

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllWithCredentials", policy =>
                {
                    policy.SetIsOriginAllowed(_ => true)
                          .AllowAnyHeader()
                          .AllowAnyMethod()
                          .AllowCredentials();
                });
            });
            return services;
        }

        public static IApplicationBuilder UseMonacoRoslynComplete(this IApplicationBuilder app)
        {
            ConfigStaticFiles(app);

            // 使用静态文件中间件
            app.UseFileServer();

            //启用控制器
            //app.UseRouting();
            //app.UseEndpoints(endpoints =>
            //{
            //    endpoints.MapControllers();
            //});

            // 使用CORS中间件
            app.UseCors("AllowAllWithCredentials");

            return app;
        }


        /// <summary>
        /// Add access to static resources on debug mode
        /// </summary>
        /// <param name="app"></param>
        private static void ConfigStaticFiles(IApplicationBuilder app)
        {
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new ManifestEmbeddedFileProvider(Assembly.GetExecutingAssembly(), "wwwroot"),
                RequestPath = new PathString("/OnlineEditors")
            });

            // 添加自定义中间件以处理重定向
            app.Use(async (context, next) =>
            {
                // 检查请求路径是否包含 "OnlineEditors"
                if (context.Request.Path.StartsWithSegments("/OnlineEditors") &&
                    context.Request.Path.Value.EndsWith("/OnlineEditors", StringComparison.OrdinalIgnoreCase))
                {
                    // 重定向到 "OnlineEditors/Index.html"
                    context.Response.Redirect("/OnlineEditors/MonacoEditors/index.html");
                    return;
                }

                // 继续处理下一个中间件
                await next();
            });
        }
    }
}
